﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using GiveGraphModel;

namespace GiveGraphMappers.ContextBalancer
{


    internal sealed class GiveGraphContextBalancer
    {

        private const int MAX_ACTIVE_CONNECTIONS = 1;

        private static volatile GiveGraphContextBalancer _balancer;

        public static GiveGraphContextBalancer Balancer
        {
            get
            {
                if (_balancer == null)
                    Interlocked.CompareExchange(ref _balancer, new GiveGraphContextBalancer(), null);
                return _balancer;
            }
        }

        private GiveGraphContextBalancer()
        {
            
        }


        private readonly MonitorBoundedQueue<GiveGraphContext> _contexts = new MonitorBoundedQueue<GiveGraphContext>(MAX_ACTIVE_CONNECTIONS);
        private volatile int _connectionsCreated = 0;

        public GiveGraphContext Get()
        {
            if (_connectionsCreated != MAX_ACTIVE_CONNECTIONS)
            {
                
                do
                {
                    var curr = _connectionsCreated;
                    if (_connectionsCreated != MAX_ACTIVE_CONNECTIONS)
                    {
                        if (Interlocked.CompareExchange(ref _connectionsCreated, curr + 1, curr) == curr)
                        {
                            return new GiveGraphContext();
                        }
                    }
                } while (_connectionsCreated != MAX_ACTIVE_CONNECTIONS);
            }
            return _contexts.Get(Timeout.Infinite);
        }

        public void Put(GiveGraphContext ctx)
        {
            _contexts.Put(ctx, Timeout.Infinite);
        }
    }
}
